<?php

namespace oa\controllers;

use Yii;
use common\models\User;
use oa\services\UserService;
use oa\services\RoleService;

class UserController extends BaseController
{
	public function actionIndex()
	{
		if ($this->request->isAjax) {
            return UserService::getList();
        }
        return $this->fetch([
			'roles' => RoleService::getAll()
		]);
	}

	public function actionAdd()
	{
		if ($this->request->isPost) {
			$res = UserService::save($this->request->post());
			if ($res === true) {
				return $this->ok('提交成功');
			}
			return $this->err('提交失败', $res);
        }
		return $this->fetch([
			'roles' => RoleService::getAll()
		], 2);
	}

	public function actionEdit()
	{
		$id = $this->input('id');
		if ($this->request->isPost) {
			$res = UserService::save($this->request->post(), $id);
			if ($res === true) {
				return $this->ok('提交成功');
			}
			return $this->err($res);
        }
		$data = UserService::one($id, 1);
		if ($data['role_id'] == -1) {
			return $this->err('超级管理员不支持修改');
		}
		return $this->fetch([
			'roles' => RoleService::getAll(),
			'data' => $data
		], 2);
	}

	public function actionRemove()
	{
		if ($this->request->isAjax) {
			if (UserService::remove($this->input('id'))) {
				return $this->ok('删除成功');
			}
			return $this->err('删除失败');
        }
	}

	public function actionDisable()
	{
		if ($this->request->isAjax) {
			if (UserService::disable($this->input('id'))) {
				return $this->ok('禁用成功');
			}
			return $this->err('禁用失败');
        }
	}

	public function actionEnable()
	{
		if ($this->request->isAjax) {
			if (UserService::enable($this->input('id'))) {
				return $this->ok('启用成功');
			}
			return $this->err('启用失败');
        }
	}

	public function actionEditPassword()
	{
		$id = $this->input('id');
		if ($this->request->isPost) {
			$res = UserService::editPassword($id);
			if ($res === true) {
				return $this->ok('保存成功');
			}
			return $this->err('保存失败', $res);
        }
		return $this->fetch([], 2);
	}

	public function actionResetPassword()
	{
		$id = $this->input('id');
		if ($this->request->isPost) {
			$res = UserService::resetPassword($id);
			if ($res === true) {
				return $this->ok('保存成功');
			}
			return $this->err('保存失败', $res);
        }
		return $this->fetch([], 2);
	}

}